<template>
  <div>
    <page-box>
      <template #top>
        <alert-msg content="传输中心下载文件只保留7天，7天后失效无法下载，请及时保存">
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="onFetchData">查询</el-button>
      </template>
      <template #table>
        <resize-table
          :showPagination="true"
          :data="tableData"
          :pagingData="pagingData"
          :headers="headers"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
        >
          <!-- 事件类型 -->
          <template #type="{ scope }">
            {{ getEventType(scope.row.type) }}
          </template>
          <!-- 事件类型 -->
          <template #status="{ scope }">
            {{ getStatusName(scope.row.status) }}
          </template>

          <template #createUser="{ scope }">
            <span class="createUser">
              {{ userObj && userObj[scope.row.createUser] ? userObj[scope.row.createUser].name : '--' }}
            </span>
          </template>
          <template #oprate="{ scope }">
            <!--有下载权限 && (失效的除外)多文件下载 =》 弹窗选择要下载的文件-->
            <span
              class="oprate-span"
              v-if="scope.row.status !== 'INVALID' && scope.row.downloadUrls && scope.row.downloadUrls.length > 1"
              @click="handleDownload(scope.row)"
              >下载</span
            >
            <!--有下载权限 && (失效的除外)单个文件，直接下载-->
            <a
              class="oprate-span"
              v-if="scope.row.status !== 'INVALID' && scope.row.downloadUrls && scope.row.downloadUrls.length === 1"
              :href="scope.row.downloadUrls[0].url + '?name=' + scope.row.downloadUrls[0].name"
              target="_blank"
              download
              >下载</a
            >
            <!--有删除载权限 &&只要不是进行中的操作 =》!（正在导出 || 排队中 || 导入中） =》 (删除操作)-->
            <span
              class="oprate-span"
              v-if="
                !(
                  scope.row.status === 'EXPORTING' ||
                  scope.row.status === 'PENDING' ||
                  scope.row.status === 'IMPORTING'
                )
              "
              @click="handleDeleteOrCancle(scope.row, 'delete')"
              >删除</span
            >
          </template>
        </resize-table>
      </template>
    </page-box>
    <multi-filed-dialog ref="multiFiledDialogRef"></multi-filed-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, onBeforeMount, getCurrentInstance, toRefs, computed, nextTick } from 'vue'
import pageBox from '@common/components/page-box.vue'
import searchForm from '@common/components/base-form/form.vue'
import resizeTable from '@common/components/resize-table/index.vue'
import alertMsg from '@common/components/alert/index.vue'
import multiFiledDialog from '@app/base/views/transmission-center/multi-filed-dialog.vue'
import { commonStore } from '@/common/store/modules/common'
import { ElMessageBox, ElMessage } from 'element-plus'
export default defineComponent({
  name: 'roleConfig',
  components: { searchForm, resizeTable, pageBox, alertMsg, multiFiledDialog },
  setup() {
    const INSTANCE: any = getCurrentInstance()
    const typeMap = [
      { label: '短信记录', value: 'sms' },
      { label: '通话记录', value: 'cdr' },
      { label: '通话录音', value: 'cdrRecordFile' },
      { label: '自动外呼', value: 'autoDialout' },
      { label: '预览外呼', value: 'previewDialout' },
      { label: '工单导出', value: 'workOrder' }
    ]
    const statusMap = [
      { label: '成功', value: 'SUCCEED' },
      { label: '部分成功', value: 'PARTIAL' },
      { label: '失败', value: 'FAILED' },
      { label: '失效', value: 'INVALID' },
      { label: '正在导出', value: 'EXPORTING' },
      { label: '导入中', value: 'IMPORTING' },
      { label: '排队中', value: 'PENDING' }
    ]
    const STATE = reactive({
      // 动态表单检索
      fieldList: [
        {
          name: '任务ID或备注',
          field: 'quickSearch',
          type: 'text'
        },
        {
          name: '任务来源',
          field: 'eventType',
          type: 'dropdown',
          choices: typeMap,
          multiple: true
        }
      ],
      // 检索表单
      form: { eventType: '' },
      // 表格数据
      tableData: [],
      headers: [
        { label: '创建时间', prop: 'createTime', show: true },
        { label: '任务ID', prop: 'taskId', show: true },
        { label: '任务来源', prop: 'type', show: true, custom: true },
        { label: '总数', prop: 'count', show: true },
        { label: '备注', prop: 'comment', show: true },
        { label: '创建人', prop: 'createUser', show: true, custom: true },
        { label: '状态', prop: 'status', show: true, custom: true },
        { label: '操作', prop: 'oprate', show: true, width: 120 }
      ],
      // 分页数据
      pagingData: { page: 1, total: 0, limit: 10 },
      getEventType: (type: string) => {
        const arr = typeMap
        let str = '--'
        arr.forEach((item: any) => {
          if (item.value === type) {
            str = item.label
          }
        })
        return str
      },
      getStatusName: (type: string) => {
        const arr = statusMap
        let str = '--'
        arr.forEach((item: any) => {
          if (item.value === type) {
            str = item.label
          }
        })
        return str
      }
    })
    // 快捷表单检索
    const searchFun = () => {
      STATE.pagingData.page = 1
      onFetchData()
    }

    // 删除推送事件
    const onDelete = (data: any) => {
      ElMessageBox.confirm('确定删除该事件类型吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ElMessage({ message: '删除成功', type: 'success' })
          onFetchData()
        })
        .catch((e) => {
          console.log(e)
        })
    }
    // 获取所有员工的map信息
    const userObj: any = computed(() => {
      return commonStore().publicCache.userCacheObj || {}
    })

    // 获取事件推送列表
    const onFetchData = () => {
      // const sendData = {
      //   ...STATE.form,
      //   limit: STATE.pagingData.limit,
      //   page: STATE.pagingData.page
      // }
      // queryServiceTime(sendData).then((res: any) => {
      //   if (res.success && res.data) {
      //     STATE.tableData = res.data.list || []
      //     STATE.pagingData.total = res.data.count || 0
      //   }
      // })
      console.log('查列表==========')
      const res: any = {
        success: true,
        message: '200 ok!',
        code: '200',
        data: {
          count: 7,
          list: [
            {
              data: [
                '109aecb7-16a2-4a95-b1d8-fe76e78abb12',
                'ee173e4f-ea7c-495b-ad05-1673c22f7e38',
                '7bea5128-b5a3-4c45-b522-96b9d84bba36',
                'b4c045f9-4314-4743-a870-cdb1e919d1b5'
              ],
              _id: '6295aae8dcdfe632ce002f48',
              accountId: '2001432',
              taskId: 'D20220531001',
              createUser: '579752078334488576',
              status: 'INVALID',
              type: 'sms',
              condition:
                '{"_id":{"$in":["109aecb7-16a2-4a95-b1d8-fe76e78abb12","ee173e4f-ea7c-495b-ad05-1673c22f7e38","7bea5128-b5a3-4c45-b522-96b9d84bba36","b4c045f9-4314-4743-a870-cdb1e919d1b5"]}}',
              count: 4,
              version: '.ykf',
              createTime: '2022-05-31 13:43:04',
              updateTime: '2022-07-01 01:00:00',
              startTime: '2022-05-31 13:43:07',
              endTime: '2022-05-31 13:43:07',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220531001.xlsx',
                  name: 'D20220531001.xlsx',
                  size: 4511,
                  path: '/nfs/ykf/exportchat/D20220531001.xlsx'
                }
              ]
            },
            {
              data: ['ee173e4f-ea7c-495b-ad05-1673c22f7e38'],
              _id: '62949afb4401c900124091cf',
              accountId: '2001432',
              taskId: 'D20220530001',
              createUser: '579752078334488576',
              comment: '',
              status: 'PENDING',
              type: 'cdrRecordFile',
              condition: '{"_id":{"$in":["ee173e4f-ea7c-495b-ad05-1673c22f7e38"]}}',
              count: 1,
              version: '.ykf',
              createTime: '2022-05-30 18:22:51',
              updateTime: '2022-06-30 01:00:00',
              startTime: '2022-05-30 18:22:57',
              endTime: '2022-05-30 18:22:57',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220530001.xlsx',
                  name: 'D20220530001.xlsx',
                  size: 4045,
                  path: '/nfs/ykf/exportchat/D20220530001.xlsx'
                },
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220530001.xlsx',
                  name: 'D20220530001.xlsx',
                  size: 4045,
                  path: '/nfs/ykf/exportchat/D20220530001.xlsx'
                }
              ]
            },
            {
              data: [],
              _id: '628378837051200012916615',
              accountId: '2001432',
              taskId: 'D20220517001',
              createUser: '580504212288270336',
              comment: '',
              status: 'INVALID',
              type: 'sessionTags',
              condition: '',
              count: 6,
              version: '.ykf',
              createTime: '2022-05-17 18:27:15',
              updateTime: '2022-06-17 01:00:00',
              startTime: '2022-05-17 18:27:21',
              endTime: '2022-05-17 18:27:21',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220517001.xlsx',
                  name: 'D20220517001.xlsx',
                  size: 3659,
                  path: '/nfs/ykf/exportchat/D20220517001.xlsx'
                }
              ]
            },
            {
              data: [
                'eec3dba9-511d-4d51-b016-6c5bad0d414e',
                '03d3f74d-7f04-40d2-960d-f328ee93b229',
                '6aceb8fe-2576-4ab0-acf1-8de598957e58',
                '0ec04b38-322a-43db-a2cf-cc3fc1845a0f',
                'b4e2a811-8ef7-4863-b326-7ab0e4499c3c',
                '5c9d33aa-c79e-43c1-8de3-1407fc4ad648',
                'aa9216ed-ccf2-4bd7-a2a0-9dd93982648a',
                '058de2eb-862e-404a-b64c-aced0777a74d',
                '7c98e9ef-f8c7-436c-a6a5-338c53660f11',
                'df597b05-64aa-4445-bb1c-c266b3361467'
              ],
              _id: '627c6c70d749650011be2ba4',
              accountId: '2001432',
              taskId: 'D20220512001',
              createUser: '580504212288270336',
              comment: '',
              status: 'PENDING',
              type: 'chatSession',
              condition:
                '{"_id":{"$in":["eec3dba9-511d-4d51-b016-6c5bad0d414e","03d3f74d-7f04-40d2-960d-f328ee93b229","6aceb8fe-2576-4ab0-acf1-8de598957e58","0ec04b38-322a-43db-a2cf-cc3fc1845a0f","b4e2a811-8ef7-4863-b326-7ab0e4499c3c","5c9d33aa-c79e-43c1-8de3-1407fc4ad648","aa9216ed-ccf2-4bd7-a2a0-9dd93982648a","058de2eb-862e-404a-b64c-aced0777a74d","7c98e9ef-f8c7-436c-a6a5-338c53660f11","df597b05-64aa-4445-bb1c-c266b3361467"]}}',
              count: 10,
              version: '.ykf',
              createTime: '2022-05-12 10:09:52',
              updateTime: '2022-06-12 01:00:00',
              startTime: '2022-05-12 10:09:53',
              endTime: '2022-05-12 10:09:53',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220512001.xlsx',
                  name: 'D20220512001.xlsx',
                  size: 5291,
                  path: '/nfs/ykf/exportchat/D20220512001.xlsx'
                }
              ]
            },
            {
              data: [
                'eec3dba9-511d-4d51-b016-6c5bad0d414e',
                '03d3f74d-7f04-40d2-960d-f328ee93b229',
                '6aceb8fe-2576-4ab0-acf1-8de598957e58',
                '0ec04b38-322a-43db-a2cf-cc3fc1845a0f',
                'b4e2a811-8ef7-4863-b326-7ab0e4499c3c',
                '5c9d33aa-c79e-43c1-8de3-1407fc4ad648',
                'aa9216ed-ccf2-4bd7-a2a0-9dd93982648a',
                '058de2eb-862e-404a-b64c-aced0777a74d',
                '7c98e9ef-f8c7-436c-a6a5-338c53660f11',
                'df597b05-64aa-4445-bb1c-c266b3361467'
              ],
              _id: '627b627bbe99ed00113050dd',
              accountId: '2001432',
              taskId: 'D20220511003',
              createUser: '6273df5af3a2d200112d861d',
              comment: '支持',
              status: 'INVALID',
              type: 'chatSession',
              condition:
                '{"_id":{"$in":["eec3dba9-511d-4d51-b016-6c5bad0d414e","03d3f74d-7f04-40d2-960d-f328ee93b229","6aceb8fe-2576-4ab0-acf1-8de598957e58","0ec04b38-322a-43db-a2cf-cc3fc1845a0f","b4e2a811-8ef7-4863-b326-7ab0e4499c3c","5c9d33aa-c79e-43c1-8de3-1407fc4ad648","aa9216ed-ccf2-4bd7-a2a0-9dd93982648a","058de2eb-862e-404a-b64c-aced0777a74d","7c98e9ef-f8c7-436c-a6a5-338c53660f11","df597b05-64aa-4445-bb1c-c266b3361467"]}}',
              count: 10,
              version: '.ykf',
              createTime: '2022-05-11 15:15:07',
              updateTime: '2022-06-11 01:00:00',
              startTime: '2022-05-11 15:15:11',
              endTime: '2022-05-11 15:15:11',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220511003.xlsx',
                  name: 'D20220511003.xlsx',
                  size: 5291,
                  path: '/nfs/ykf/exportchat/D20220511003.xlsx'
                }
              ]
            },
            {
              data: [
                'eec3dba9-511d-4d51-b016-6c5bad0d414e',
                '03d3f74d-7f04-40d2-960d-f328ee93b229',
                '6aceb8fe-2576-4ab0-acf1-8de598957e58',
                '0ec04b38-322a-43db-a2cf-cc3fc1845a0f',
                'b4e2a811-8ef7-4863-b326-7ab0e4499c3c',
                '5c9d33aa-c79e-43c1-8de3-1407fc4ad648',
                'aa9216ed-ccf2-4bd7-a2a0-9dd93982648a',
                '058de2eb-862e-404a-b64c-aced0777a74d',
                '7c98e9ef-f8c7-436c-a6a5-338c53660f11',
                'df597b05-64aa-4445-bb1c-c266b3361467'
              ],
              _id: '627b625bbe99ed00113050dc',
              accountId: '2001432',
              taskId: 'D20220511002',
              createUser: '6273df5af3a2d200112d861d',
              comment: '',
              status: 'INVALID',
              type: 'chatSession',
              condition:
                '{"_id":{"$in":["eec3dba9-511d-4d51-b016-6c5bad0d414e","03d3f74d-7f04-40d2-960d-f328ee93b229","6aceb8fe-2576-4ab0-acf1-8de598957e58","0ec04b38-322a-43db-a2cf-cc3fc1845a0f","b4e2a811-8ef7-4863-b326-7ab0e4499c3c","5c9d33aa-c79e-43c1-8de3-1407fc4ad648","aa9216ed-ccf2-4bd7-a2a0-9dd93982648a","058de2eb-862e-404a-b64c-aced0777a74d","7c98e9ef-f8c7-436c-a6a5-338c53660f11","df597b05-64aa-4445-bb1c-c266b3361467"]}}',
              count: 10,
              version: '.ykf',
              createTime: '2022-05-11 15:14:35',
              updateTime: '2022-06-11 01:00:00',
              startTime: '2022-05-11 15:14:39',
              endTime: '2022-05-11 15:14:39',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220511002.xlsx',
                  name: 'D20220511002.xlsx',
                  size: 5291,
                  path: '/nfs/ykf/exportchat/D20220511002.xlsx'
                }
              ]
            },
            {
              data: [
                'eec3dba9-511d-4d51-b016-6c5bad0d414e',
                '03d3f74d-7f04-40d2-960d-f328ee93b229',
                '6aceb8fe-2576-4ab0-acf1-8de598957e58',
                '0ec04b38-322a-43db-a2cf-cc3fc1845a0f',
                'b4e2a811-8ef7-4863-b326-7ab0e4499c3c',
                '5c9d33aa-c79e-43c1-8de3-1407fc4ad648',
                'aa9216ed-ccf2-4bd7-a2a0-9dd93982648a',
                '058de2eb-862e-404a-b64c-aced0777a74d',
                '7c98e9ef-f8c7-436c-a6a5-338c53660f11',
                'df597b05-64aa-4445-bb1c-c266b3361467'
              ],
              _id: '627b61dd75182800125aa7f0',
              accountId: '2001432',
              taskId: 'D20220511001',
              createUser: '6273aec5ccfa1200114a77ba',
              comment: '',
              status: 'INVALID',
              type: 'chatSession',
              condition:
                '{"_id":{"$in":["eec3dba9-511d-4d51-b016-6c5bad0d414e","03d3f74d-7f04-40d2-960d-f328ee93b229","6aceb8fe-2576-4ab0-acf1-8de598957e58","0ec04b38-322a-43db-a2cf-cc3fc1845a0f","b4e2a811-8ef7-4863-b326-7ab0e4499c3c","5c9d33aa-c79e-43c1-8de3-1407fc4ad648","aa9216ed-ccf2-4bd7-a2a0-9dd93982648a","058de2eb-862e-404a-b64c-aced0777a74d","7c98e9ef-f8c7-436c-a6a5-338c53660f11","df597b05-64aa-4445-bb1c-c266b3361467"]}}',
              count: 10,
              version: '.ykf',
              createTime: '2022-05-11 15:12:29',
              updateTime: '2022-06-11 01:00:00',
              startTime: '2022-05-11 15:12:36',
              endTime: '2022-05-11 15:12:36',
              elapsedSeconds: 0,
              downloadUrls: [
                {
                  url: 'https://v7.7moor.com/download/exportchat/D20220511001.xlsx',
                  name: 'D20220511001.xlsx',
                  size: 5291,
                  path: '/nfs/ykf/exportchat/D20220511001.xlsx'
                }
              ]
            }
          ]
        }
      }
      const list = res.data.list || []
      if (list.length === 0) {
        const page = Math.ceil(res.data.count / STATE.pagingData.limit)
        if (!res.data.count) {
          // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
          STATE.pagingData.page = 1
        } else {
          // 删除到最后一个回到上一页
          STATE.pagingData.page = page
          onFetchData()
          return false
        }
      }
      STATE.tableData = res.data.list || []
      STATE.pagingData.total = res.data.count || 0
    }
    const handleCurrentChange = (page: number) => {
      STATE.pagingData.page = page
      onFetchData()
    }

    const handleSizeChange = (size: number) => {
      STATE.pagingData.limit = size
      onFetchData()
    }
    // 处理下载多文件
    const handleDownload = (row: any) => {
      const downloadList = row.downloadUrls || []
      downloadList.forEach((item: any) => {
        if (item.size && typeof item.size === 'number') {
          item.size = `${Math.ceil(item.size / 1024 / 1024)}M` // 从B换算成M
          if (item.size > 1024) {
            item.size = `${Math.ceil(item.size / 1024)}G` // 从M换算成G
          }
        }
      })
      INSTANCE?.refs.multiFiledDialogRef.setDialogData(downloadList)
    }
    // 删除或者取消某个任务
    const handleDeleteOrCancle = (row: any, type: string) => {
      ElMessageBox.confirm(`确定要${type === 'delete' ? '删除' : '取消'}此任务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // const actionData = { taskId: row.taskId }
          // const data = { url: '/base/action/transmission/export/task/cancel', method: 'POST', data: actionData }
          // if (type === 'delete') {
          //   data.url = this.moduleType === 'import' ? '/base/action/transmission/import/task/delete' : '/base/action/transmission/export/task/delete'
          // }
          onFetchData()
          ElMessage({ message: '删除成功', type: 'success' })
        })
        .catch(() => {
          console.log('取消')
        })
    }
    // 首次获取列表
    onBeforeMount(() => {
      onFetchData()
    })
    return {
      ...toRefs(STATE),
      onFetchData,
      handleCurrentChange,
      handleSizeChange,
      searchFun,
      onDelete,
      userObj,
      handleDownload,
      handleDeleteOrCancle
    }
  }
})
</script>

<style lang="stylus" scoped>
.oprate-span
  color var(--mc-main-color)
  cursor pointer
  padding-right 10px
  text-decoration-line none
</style>
